package com.afishing.servlet;

import com.afishing.dao.CartDao;
import com.afishing.dao.impl.CartDapImpl;
import com.afishing.entity.Shop;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "AddCartServlet", value = "/addCart")
public class AddCartServlet extends HttpServlet {
    private final CartDao cartDao = new CartDapImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        // 从请求中获取购物车数据
        String cartJson = request.getReader().lines().reduce("", (accumulator, actual) -> accumulator + actual);

        //解析json字符串
        List<Shop> cartItems = JSONObject.parseArray(cartJson, Shop.class);
        System.out.println(cartItems);

        // 将数据插入数据库
        for (Shop item : cartItems) {
            cartDao.addShop(item);
        }

        // 返回响应给客户端
        response.getWriter().write("success");

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}